<template>
  <div id="map">
    <div class="person" id="svgBox">
      <div class="nyimg">
        <img src="../../public/image/ny.png" alt width="100%" height="100%" />
      </div>
      <div class="svgWrap">
        <svg
          class="svg"
          width="1195"
          height="821"
          viewBox="0 0 1195 821"
          ref="svg"
          xmlns="http://www.w3.org/2000/svg"
        >
        <!-- <image href="../../public/image/3.png" /> -->
        </svg>
      </div>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import axios from "axios";
import { baseEnv } from "@/request";
let baseUrl;
let moveTimer = null;
let isStop = {};
var dStr = {}; // 记录d的str
var paths;
var rem2;
const APIURL = require("../../public/ipConfigtest");
rem2 = 85.3;
export default {
  data() {
    return {
      src: ""
      // Drawpath: "M10 ,10"
    };
  },
  mounted() {
    if (baseEnv == "development") {
      baseUrl = "/b";
    } else {
      baseUrl = "https://overall.qcdoc.cn/";
      // baseUrl = `${APIURL.BASE_URL}/customer-aim`;
    }
    // 电子围栏
    let polygonArr = [];
    this.axios
      .get(`${baseUrl}/location/getFence?id=2`, {
        headers: {
          "Content-Type": "application/json;charset=UTF-8"
        }
      })
      .then(res => {
        let data = (res.data.data && res.data.data.vertex) || [];
        var keyMap = {
          X: "x",
          Y: "y",
          Z: "z"
        };
        data.forEach((el, index) => {
          // 外层
          el.forEach(e => {
            for (var key in e) {
              var newKey = keyMap[key];
              if (newKey) {
                e[newKey] = e[key];
                delete e[key];
              } else {
                delete e[key];
              }
            }
          });
          polygonArr.push(el);
        });

        for (let i = 0; i < polygonArr.length; i++) {
          let point = polygonArr[i];
          let pointsStr = "";
          for (let j = 0; j < polygonArr[i].length; j++) {
            pointsStr += `${polygonArr[i][j].x},${polygonArr[i][j].y} `;
          }
          this.createPolygonMaker(pointsStr);
        }
      });
    // 监听弹框事件
    this.$nextTick(() => {
      var domMap;
      var domIds = [];
      var id;
      var svg = document.getElementById("svgBox");

      svg.addEventListener("click", ev => {
        console.log("clcik");

        var target = ev.target;
        var box = target.parentNode;
        console.log(target.tagName);

        if (target.tagName.toLowerCase() == "img") {
          domMap = target.dataset; // data属性
          let index = arr.findIndex(el => {
            return el.id == parseInt(domMap.id);
          });
          domMap.x = arr[index].x;
          domMap.y = arr[index].y;
          domIds.push(domMap.id);
          let con = this.showPop(domMap);

          $(box).prepend(con);
        } else if (target.tagName.toLowerCase() == "div") {
          let i = domIds.findIndex(el => {
            return el == id;
          });
          id = target.parentNode.dataset.id;
          $(`#popbox${id}`).remove();
        }
      });
    });
    //  运动轨迹
    let arr = [];
    this.axios
      .get(`${baseUrl}/location/getPosInfo`, {
        headers: {
          "Content-Type": "application/json;charset=UTF-8"
        }
      })
      .then(res => {
        const alldata = res.data.data; //获取所有人点位信息
        res.data.data.forEach(el => {
          if (el.tagId == 418222 || el.tagId == 416631 || el.tagId == 430054) {
            el.type = 0;
          } else {
            el.type = 3;
          }
          let id = el.tagId;
          switch (id) {
            case 416631:
              el.name = "陶程";
              break;
            case 418222:
              el.name = "杨杰";
              break;
            case 430054:
              el.name = "钱海";
              break;
            default:
              el.name = "访客";
              break;
          }
          arr.push({
            id: el.tagId,
            type: el.type,
            name: el.name,
            x: parseFloat(el.posX),
            y: parseFloat(el.posY)
          });
        });
        var list = document.getElementsByClassName("person");
        var frag = document.createDocumentFragment();
        var frag2 = document.createDocumentFragment();
        var svgBox = document.getElementsByClassName("svg");
        for (let i = 0; i < arr.length; i++) {
          this.createPerson(
            arr[i].x,
            arr[i].y,
            arr[i].type,
            arr[i].name,
            arr[i].id,
            i,
            frag
          );
          this.createpathMaker(arr[i].x, arr[i].y, frag2);
        }
        list[0].appendChild(frag);
        svgBox[0].appendChild(frag2);
        moveRoute();
      });
    // 单条线
    // 定时获取点位信息
    var that = this;
    function moveRoute() {
      //坐标点存储器
      var start = performance.now();
      var boxs = document.querySelectorAll(".personDivWrap"); // 人的盒子
      paths = document.querySelectorAll("path"); // 轨迹path
      var rafId = {}; //批量定义
      var point = {}; // 记录上一个值
      var lens = {}; // 记录最新的path长度
      // var dStr = {}; // 记录d的str
      var patharrs = {}; // 记录点位数组
      for (var j = 0; j < arr.length; j++) {
        var pointName = "point" + j; //动态定义变量名
        point[pointName] = { x: arr[j].x, y: arr[j].y }; //动态赋值
        var lenName = "len" + j;
        lens[lenName] = [];
        var rafIdName = "rafId" + j;
        rafId[rafIdName] = null;
        var pathArrName = "path" + j;
        patharrs[pathArrName] = [];
        var strName = "str" + j;
        dStr[strName] = `M${arr[j].x},${arr[j].y}`;
        var stopName = "stop" + j;
        isStop[stopName] = false;
        // 每条路径的总长度
        lens[`len${j}`] = paths[j].getTotalLength() || 0;

        // 人跟随运动
        // that.frame(
        //   lens[`len${j}`],
        //   isStop[`stop${j}`],
        //   boxs[j],
        //   start,
        //   paths[j],
        //   rafId[`rafId${j}`]
        // );
      }
      // point[`point${i}`]
      moveTimer = setInterval(() => {
        that.axios
          .get(`${baseUrl}/location/getPosInfo`, {
            headers: {
              "Content-Type": "application/json;charset=UTF-8"
            }
          })
          .then(res => {
            const alldata = res.data.data; //获取所有人点位信息
            for (let k = 0; k < arr.length; k++) {
              let pointArr = [alldata[k].posX, alldata[k].posY]; // 最新的点位
              // let pathArr = point[`point${k}`];
              if (arr[k].id == alldata[k].tagId) {
                //过滤前后重复的
                if (point[`point${k}`]) {
                  var chge = that.ckSamePt(point[`point${k}`], {
                    x: alldata[k].posX,
                    y: alldata[k].posY
                  });
                  if (chge) {
                    continue;
                  }
                }

                point[`point${k}`] = {
                  x: alldata[k].posX,
                  y: alldata[k].posY
                };
                // 画线patharrs[pathArrName]
                that.setPath(pointArr, patharrs[`path${k}`], k);
                // that.frame(lens[`len${k}`], boxs[k], start, paths[k]);
                that.frame(point[`point${k}`], boxs[k], arr[k]);
              }
            }
          });
      }, 1000);
    }

    var that = this;
    window.addEventListener("resize", refresh(), false);
    function refresh() {
      var docEl = window.document.documentElement;
      var width = docEl.getBoundingClientRect().width;
      // if (width < 1366) {
      //   rem = width / 24;
      // } else if (width > 2560) {
      //   rem = width / 24;
      // } else {
      //   rem = width / 24;
      // }
    }
    refresh();
    var rem2;
    rem2 = 85.3;
  },
  destroyed() {
    clearInterval(moveTimer);
  },
  methods: {
    /**
     * @pointArr 实时点位
     * @pathArr  path点位的数组
     * @path 轨迹path的dom结构
     */
    setPath(pointArr, pathArr, k) {
      pathArr.push([...pointArr]);
      // that.Drawpath += `L${pointArr[0]},${pointArr[1]}`;
      if (pathArr.length > 5) {
        let prePonit = pathArr.shift();
        let pathTemp = dStr[`str${k}`].split("L");
        pathTemp.splice(0, 1);
        let str = "";
        for (let i = 0; i < pathTemp.length; i++) {
          if (i == 0) {
            pathTemp[i] = `M${pathTemp[i]}`;
          } else if (i == pathTemp.length - 1) {
            let arr = pathTemp[i].split("M");
            pathTemp[i] = `L${arr[0]}M${arr[1]}`;
          } else {
            pathTemp[i] = `L${pathTemp[i]}`;
          }
          str += `${pathTemp[i]}`;
        }
        dStr[`str${k}`] = str;
        // 设置path值
        paths[k].setAttribute("d", dStr[`str${k}`]);
        dStr[`str${k}`] = `${dStr[`str${k}`]}L${pointArr[0]},${pointArr[1]} M${
          pointArr[0]
        },${pointArr[1]}`;
      } else {
        let pathTemp = dStr[`str${k}`].split("M");
        pathTemp.length > 2 ? pathTemp.splice(pathTemp.length - 1, 2) : null;
        pathTemp.length > 1 ? pathTemp.splice(0, 1) : null;
        pathTemp[0] = `M${pathTemp[0]}`;
        dStr[`str${k}`] = pathTemp[0];
        console.log(pathTemp[0]);
        paths[k].setAttribute("d", dStr[`str${k}`]);

        dStr[`str${k}`] = `${dStr[`str${k}`]}L${pointArr[0]},${pointArr[1]} M${
          pointArr[0]
        },${pointArr[1]}`;
      }
    },
    // rafIds,
    frame(point, box, arr) {
      box.style.transform =
        "translate3d(" +
        (point.x - arr.x) / rem2 +
        "rem," +
        (point.y - arr.y - 8) / rem2 +
        "rem,0)"; // IE
      box.style.WebkitTransform =
        "translate3d(" +
        (point.x - arr.x) / rem2 +
        "rem," +
        (point.y - arr.y - 8) / rem2 +
        "rem,0)"; // Chrome&Safari
    },
    createPerson(x, y, type, name, id, i, frag) {
      // var wrapObgj = document.createElementNS(
      //   "http://www.w3.org/2000/svg",
      //   "foreignObject"
      // );
      var personDiv = document.createElement("div"); // 父盒子
      var imgDiv = document.createElement("div"); // 子盒子
      var person = document.createElement("img"); // 子元素
      person.className = "imgName";
      imgDiv.className = "imgDiv" + i;
      var svg = document.getElementsByClassName("svgWrap");
      personDiv.className = "personDivWrap personDiv" + i;
      if (type == 0) {
        this.src = require("../../public/image/0.png");
      } else {
        this.src = require("../../public/image/3.png");
      }
      person.src = this.src;
      person.setAttribute("data-id", id);
      person.setAttribute("data-name", name);
      person.setAttribute("data-type", type);
      // $(person)
      //   // .addClass("person")
      //   .css({
      //     width: 32,
      //     height: 32,
      //     // position: "relative",
      //     position: "absolute",
      //     top: x - 16,
      //     left: y - 16,
      //     zIndex: 10
      //   })
      //   .appendTo(".person");
      // .appendTo(".imgDiv");
      // $(wrapObgj).css({
      //   width: 16,
      //   height: 16,
      //   top:(x-8),
      //   left:(y-8),
      //   // top: (y - 8) / rem2 + "rem",
      //   // left: (x - 8) / rem2 + "rem",
      //   position: "absolute",
      //   zIndex: 20
      // });
      // frag.appendChild(wrapObgj);
      $(personDiv).css({
        width: 16,
        height: 16,
        // top: (y / svg[0].offsetHeight / 0.93) * 100 + "%",
        // left: (x / svg[0].offsetWidth) * 100 + "%",
        top: (y - 8) / rem2 + "rem",
        left: (x - 8) / rem2 + "rem",
        position: "absolute",
        zIndex: 20
      });
      frag.appendChild(personDiv);
      // .appendTo(`.person`);
      $(imgDiv).css({
        width: 16,
        height: 16,
        position: "relative"
      });
      frag.appendChild(personDiv).appendChild(imgDiv);
      // .appendTo(`.personDiv${i}`);
      $(person).css({
        width: 16,
        height: 16
      });
      frag
        .appendChild(personDiv)
        .appendChild(imgDiv)
        .appendChild(person);
      // .appendTo(`.imgDiv${i}`);
    },
    createPolygonMaker(coords) {
      var polygon = document.createElementNS(
        "http://www.w3.org/2000/svg",
        "polygon"
      );
      polygon.setAttribute("points", coords);
      polygon.setAttribute(
        "style",
        "fill:#ff57004d;stroke:#f50;stroke-width:4;"
      );
      $(polygon).appendTo(".svg");
    },
    createpathMaker(x, y, frag2) {
      var pathMaker = document.createElementNS(
        "http://www.w3.org/2000/svg",
        "path"
      );
      pathMaker.setAttribute("class", "testPath");
      pathMaker.setAttribute("d", `M${x},${y}`);
      pathMaker.setAttribute("stroke", "#f50");
      pathMaker.setAttribute(
        "style",
        "fill:none;stroke :#f50;stroke-width:2px;"
      );
      // $(pathMaker).appendTo(".svg");
      frag2.appendChild(pathMaker);
    },
    // 判断两点是否相等
    ckSamePt(p1, p2) {
      if (Math.abs(p1.x - p2.x) < 0.0001 && Math.abs(p1.y - p2.y) < 0.0001) {
        //判断两点间距离
        return true;
      }
      return false;
    },
    showPop(data) {
      var types = {
        "1": "摄像头",
        "2": "消防设备",
        "3": "员工",
        "0": "访客"
      };
      let content =
        `<div class="popbox" id="popbox${data.id}" data-id="${data.id}" style="top:32px;left:0px;">` +
        '<div class="title"><span style="margin: 20px;">信息弹框</span></div>' +
        '<div class="m-box">' +
        '<div class="m-text">' +
        "<p>" +
        '<span class="m-span">id</span>' +
        '<span class="m-span">名称</span>' +
        '<span class="m-span">类型</span>' +
        "</p>" +
        "<p>" +
        '<span class="m-span2">' +
        data.id +
        "</span>" +
        '<span class="m-span2 status">' +
        data.name +
        "</span>" +
        '<span class="m-span2 ">' +
        types[data.type] +
        "</span>" +
        "</p>" +
        "</div>" +
        "</div>" +
        '<div class="myPopClose ' +
        "rock-box m-pop" +
        '"></div>' +
        "</div>";
      return content;
    }
  }
};
</script>

<style>
#map {
  width: 100%;
  height: 100%;
  position: relative;
  z-index: 10;
}
#map img {
  width: 100%;
  height: 100%;
}
.person {
  width: 100%;
  height: 100%;
  position: relative;
}
.svgWrap {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 10;
}
.svg,
.nyimg {
  width: 100%;
  height: 100%;
}
.svg {
  will-change: all;
  height: auto;
}

.popbox {
  width: 3rem;
  position: absolute;
  z-index: 100;
  background-color: cadetblue;
}
.title_p {
  border-left: 5px solid #09f;
  font-weight: 700;
  font-size: 0.8vw;
  line-height: 16px;
  padding-left: 10px;
  color: #333;
  margin-bottom: 12px;
}

#toolcheck {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
  display: none;
}

#content {
  display: flex;
  justify-content: center;
  height: 100%;
  /* box-shadow: rgba(0, 0, 0, 0.3) 2px 2px 3px; */
  position: relative;
  width: 100%;
  /* overflow: hidden; */
  margin-top: -0.5rem;
  /* background-color: black; */
}

#map-container {
  height: 100%;
  width: 100%;
  /* height: 800px;
  width: 80%; */
  position: relative;
}

.viewmode-group {
  position: absolute;
  right: 12px;
  top: 160px;
  border-radius: 6px;
  border: none;
}

.viewmode-group button {
  display: inline-block;
  width: 38px;
  height: 38px;
  border-radius: 4px;
  border: none;
  background-image: url("../../public/image/wedgets/3D.png");
}

.testPath {
  stroke-dasharray: 5000;
  stroke-dashoffset: 5000;
  animation: dash 1s linear 1;
  animation-fill-mode: forwards;
}

@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}
</style>